﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.Utils;
using DevExpress.XtraCharts;
using Lamex.Interface;

namespace Lamex.mCapacity.UI
{
    public partial class frmCAP_Owed_Analysis_Summarize : frmBaseChild
    {
        string strSql_Dept;
        string strSql_Station;
        string strSql_Process;

        public frmCAP_Owed_Analysis_Summarize()
        {
            InitializeComponent();
        }

        private void frmCAP_Owed_Analysis_Summarize_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        private void frmCAP_Analysis_Owed_Resize(object sender, EventArgs e)
        {
            //防止主窗体最小化时报错
            try
            {
                panel_R2.Height = (this.Height - panelTop.Height - panel_R1.Height) / 2;
                panel_R3.Height = panel_R2.Height;

                splitContainer1.SplitterDistance = (this.Width - panel_R1_1.Width) / 3;
                splitContainer2.SplitterDistance = splitContainer1.SplitterDistance;

                splitContainer3.SplitterDistance = splitContainer1.SplitterDistance;
                splitContainer4.SplitterDistance = splitContainer1.SplitterDistance;
                splitContainer5.SplitterDistance = splitContainer1.SplitterDistance;
                splitContainer6.SplitterDistance = splitContainer1.SplitterDistance;
            }
            catch (Exception ex)
            {
            }
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            using (WaitDialogForm wdf = new WaitDialogForm("请稍侯", "数据分析中......", new Size(400, 80)))
            {
                string strSelection = comboBox1.Text.ToString();
                switch (strSelection)
                {
                    case "全部":
                        strSql_Dept = getSqlQuery_Dept("") + @") AS a";
                        strSql_Dept = strSql_Dept + getSqlQuery_Dept_Union();
                        strSql_Station = getSqlQuery_Station("") + @") AS a";
                        strSql_Process = getSqlQuery_Process("");
                        break;
                    default:
                        strSql_Dept = getSqlQuery_Dept(@" HAVING 分厂=" + @"'" + strSelection + @"'") + @") AS a";
                        strSql_Station = getSqlQuery_Station(@" WHERE 分厂=" + @"'" + strSelection + @"'") + @") AS a";
                        strSql_Process = getSqlQuery_Process(@" WHERE 分厂=" + @"'" + strSelection + @"'");
                        break;
                }

                DataTable dt1 = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql_Dept);
                setData_Grid(dt1, gridControl1, gridView1);
                setData_Chart(dt1, chartControl1, "分厂");

                DataTable dt2 = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql_Station);
                setData_Grid(dt2, gridControl2, gridView2);
                setData_Chart(dt2, chartControl2, "工作站");

                DataTable dt3 = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql_Process);
                setData_Grid(dt3, gridControl3, gridView3);
                setData_Chart(dt3, chartControl3, "工序名称");
            }
        }

        private void setData_Grid(DataTable dt, DevExpress.XtraGrid.GridControl gc, DevExpress.XtraGrid.Views.Grid.GridView gv)
        {
            gc.DataSource = dt;
            //setGridViewColumnAutoWidth(gv);
            gv.OptionsBehavior.Editable = false;
            gv.OptionsView.ColumnAutoWidth = true;
            gv.Columns[0].BestFit();
            gv.Columns[1].BestFit();
            //gridView3.BestFitColumns();
            //setGridViewColumnAutoWidth();
        }

        private void setData_Chart(DataTable dt, ChartControl chart, string strType)
        {
            chart.Series.Clear();

            if (dt.Rows.Count != 0)
            {
                Series series1 = new Series("", ViewType.Line);

                foreach (DataRow dr in dt.Rows)
                {
                    SeriesPoint p = new SeriesPoint();

                    if (checkBox1.Checked == true)
                    {
                        //因处理不了SYSTEM.DBNull报错，已强制在SQL语句中已将DBNull转换为0
                        //原值显示
                        //防止NULL值报错
                        if (int.Parse(dr["排产天数"].ToString()) != 0)  //不能用NULL代替空
                        {
                            double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr["欠货vs定员"].ToString())), 2).ToString()) };
                            p.Values = d;
                            setPointArgument(dr, strType, p);
                            series1.Points.Add(p);
                        }
                    }
                    //不过滤消除0值及NULL值
                    else
                    {
                        double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr["欠货vs定员"].ToString())), 2).ToString()) };
                        p.Values = d;
                        setPointArgument(dr, strType, p);
                        series1.Points.Add(p);
                    }
                }

                chart.Series.Add(series1);
                chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
                Legend Legends = (Legend)chart.Legend;
                Legends.Visibility = DevExpress.Utils.DefaultBoolean.True;
                Legends.AlignmentVertical = LegendAlignmentVertical.Top;
                Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
                Legends.TextVisible = true;

                //强制显示所有x轴标签
                XYDiagram diagram = ((XYDiagram)chart.Diagram);
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagram.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;

                //设置Series的标签
                series1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据
            }
        }

        //排除因IE_WorkCenter_Definition、OP_MGT_Factory_Workstation、OP_MGT_Workstation_Process三个表中
        //PROCESS_CODE、WORKSTATION未同步定义，导致x轴标签出现NULL值，Argument报错，
        public void setPointArgument(DataRow dr, string strType, SeriesPoint p)
        {
            if (dr[strType].ToString()=="")
            {
                p.Argument = "NULL";
            }
            else
            {
                p.Argument = dr[strType].ToString();
            }
        }

        public static int ParseInt(object obj)
        {
            int reInt = -1;
            if (obj != null)
            int.TryParse(obj.ToString(), out reInt);
            return reInt;
        }

        #region 获取SQL查询语句

        private string getSqlQuery_Dept(string strQuery)
        {
            //用ISNULL(引用数据列,强制转换值)，将NULL值强制转换成特定值
            string strSql = @"							SELECT 分厂,当前定员,ISNULL(排产天数,0) AS 排产天数,欠货工时,
							CASE WHEN 排产天数=0 THEN 0 ELSE CAST(ISNULL(欠货工时/(计划排时*排产天数),0) AS decimal(18,2)) END AS 欠货vs定员						
							FROM
							(SELECT 分厂,CAST(SUM(欠货工时) AS decimal(18,0)) AS 欠货工时,
                            SUM(当前定员) AS 当前定员,
                            CAST(SUM(计划排时*当前定员) AS DECIMAL(18,0)) AS 计划排时,
                            FLOOR(SUM(欠货工时)/SUM(计划排时*当前定员)) AS 排产天数
                            FROM View_OP_Capacity_Owed_Analize
                            GROUP BY 分厂" + strQuery;
            return strSql;
        }

        private string getSqlQuery_Dept_Union()
        {
            string strUnion = @"							 UNION ALL
							SELECT '汇总',当前定员,ISNULL(排产天数,0) AS 排产天数,欠货工时,
							CASE WHEN 排产天数=0 THEN 0 ELSE CAST(ISNULL(欠货工时/(计划排时*排产天数),0) AS decimal(18,2)) END AS 欠货vs定员						
							FROM
							(SELECT CAST(SUM(欠货工时) AS decimal(18,0)) AS 欠货工时,
                            SUM(当前定员) AS 当前定员,
                            CAST(SUM(计划排时*当前定员) AS DECIMAL(18,0)) AS 计划排时,
                            FLOOR(SUM(欠货工时)/SUM(计划排时*当前定员)) AS 排产天数
                            FROM View_OP_Capacity_Owed_Analize) AS b
                            ORDER BY 欠货工时";
            return strUnion;

        }

        private string getSqlQuery_Station(string strQuery)
        {
//            string strSql = @"						SELECT 工作站,当前定员,ISNULL(排产天数,0) AS 排产天数,欠货工时,
//						CASE WHEN 排产天数=0 THEN 0 ELSE CAST(ISNULL(欠货工时/(计划排时*排产天数),0) AS decimal(18,2)) END AS 欠货vs定员						
//						FROM					
//						(SELECT 工作站,CAST(SUM(欠货工时) AS decimal(18,0)) AS 欠货工时,
//                        SUM(当前定员) AS 当前定员,
//                        CAST(SUM(计划排时*当前定员) AS DECIMAL(18,0)) AS 计划排时,
//                        FLOOR(SUM(欠货工时)/SUM(计划排时*当前定员)) AS 排产天数
//                        FROM View_OP_Capacity_Owed_Analize"
//                        + strQuery + @" GROUP BY 工作站";

            string strSql = @"SELECT 工作站,当前定员,ISNULL(排产天数,0) AS 排产天数,欠货工时,
						CASE WHEN 排产天数=0 THEN 0 ELSE CAST(ISNULL(欠货工时/(计划排时*排产天数),0) AS decimal(18,2)) END AS 欠货vs定员						
						FROM					
						(SELECT 工作站,CAST(SUM(欠货工时) AS decimal(18,0)) AS 欠货工时,
                        SUM(当前定员) AS 当前定员,
                        CAST(SUM(计划排时*当前定员) AS DECIMAL(18,0)) AS 计划排时,
                        FLOOR(SUM(欠货工时)/SUM(计划排时*当前定员)) AS 排产天数
                        FROM View_OP_Capacity_Owed_Analize"
                        + strQuery + @"
						GROUP BY 工作站";
            return strSql;
        }

        private string getSqlQuery_Process(string strQuery)
        {
            string strSql = @"SELECT 工序代码,工序名称,计划排时,当前定员,
                            ISNULL(排产天数,0) AS 排产天数,欠货工时,ISNULL(欠货vs定员,0) AS 欠货vs定员
                            FROM View_OP_Capacity_Owed_Analize" + 
                            strQuery + @" ORDER BY 工序代码";
            return strSql;
        }

        #endregion

        private void setGridViewColumnAutoWidth(DevExpress.XtraGrid.Views.Grid.GridView gv)
        {
            gv.OptionsView.ColumnAutoWidth = true;
            gv.Columns[0].BestFit();
            //for (int i = 0; i < gv.Columns.Count; i++)
            //{
            //    gv.BestFitColumns();
            //    gv.Columns[i].BestFit();//自动列宽
            //}
        }

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 0;
            panel_R2.Height = (this.Height - panelTop.Height - panel_R1.Height) / 2;
            panel_R3.Height = panel_R2.Height;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 60;
            panel_R2.Height = (this.Height - panelTop.Height - panel_R1.Height) / 2;
            panel_R3.Height = panel_R2.Height;
        }

        //gridView仅复制单元格内容，复制选中行焦点单元格的值
        private void gridView3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gridView3.GetFocusedRowCellValue(gridView3.FocusedColumn));
                e.Handled = true;
            }

            //或设置属性
            //optionBehavior - CopyToClipboardWithColumnHeader = false;
            //optionSelection - MultiSelectMode = CellSelect;
        }

        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            setLayoutGrid();
        }

        private void splitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
        {
            setLayoutGrid();
        }

        private void setLayoutGrid()
        {
            //防止主窗体最小化时报错
            try
            {
                splitContainer3.SplitterDistance = splitContainer1.SplitterDistance;
                splitContainer5.SplitterDistance = splitContainer1.SplitterDistance;

                splitContainer4.SplitterDistance = splitContainer2.SplitterDistance;
                splitContainer6.SplitterDistance = splitContainer2.SplitterDistance;
            }
            catch (Exception ex)
            {
            }
        }
    }
}